package com.power.using.mybomb.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.github.promeg.pinyinhelper.Pinyin;
import com.power.using.mybomb.R;
import com.power.using.mybomb.adapter.ContactAdapter;
import com.power.using.mybomb.adapter.IMutlipleItem;
import com.power.using.mybomb.adapter.OnRecyclerViewListener;
import com.power.using.mybomb.base.ParentWithNaviActivity;
import com.power.using.mybomb.base.ParentWithNaviFragment;
import com.power.using.mybomb.bean.Friend;
import com.power.using.mybomb.bean.User;
import com.power.using.mybomb.event.RefreshEvent;
import com.power.using.mybomb.model.UserModel;
import com.power.using.mybomb.ui.ChatActivity;
import com.power.using.mybomb.ui.NewFriendActivity;
import com.power.using.mybomb.ui.SearchUserActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by 聪明一只哈 on 2020/3/23.
 * Time: 2020/3/23  9:12
 */
public class ContractFragment extends ParentWithNaviFragment {

    @BindView(R.id.rc_view)
    RecyclerView rc_view;
    @BindView(R.id.sw_refresh)
    SwipeRefreshLayout sw_refresh;
    ContactAdapter adapter;
    LinearLayoutManager layoutManager;

    @Override
    protected String title() {
        return "联系人";
    }

    @Override
    public Object right() {
        return R.drawable.base_action_bar_add_bg_selector;
    }

    @Override
    public ParentWithNaviActivity.ToolBarListener setToolBarListener() {
        return new ParentWithNaviActivity.ToolBarListener() {
            @Override
            public void clickLeft() {

            }

            @Override
            public void clickRight() {
                startActivity(SearchUserActivity.class,null);
            }
        };
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        rootView=inflater.inflate(R.layout.fragment_conversation,container,false);
        initNaviView();
        ButterKnife.bind(this,rootView);
        IMutlipleItem<Friend> mutlipleItem=new IMutlipleItem<Friend>() {
            @Override
            public int getItemLayoutId(int viewtype) {

                if(viewtype==ContactAdapter.TYPE_NEWFRIEND){
                    return R.layout.header_new_friend;
                }else{
                    return R.layout.item_contact;
                }

            }

            @Override
            public int getItemViewType(int postion, Friend friend) {

                if(postion==0){
                    return ContactAdapter.TYPE_NEWFRIEND;
                }else{
                    return ContactAdapter.TYPE_ITEM;
                }

            }

            @Override
            public int getItemCount(List<Friend> list) {
                return list.size()+1;
            }
        };
        adapter = new ContactAdapter(getActivity(), null, mutlipleItem);
        rc_view.setAdapter(adapter);
        layoutManager = new LinearLayoutManager(getActivity());
        rc_view.setLayoutManager(layoutManager);
        sw_refresh.setEnabled(true);
        setListener();
        return rootView;
    }

    private void setListener() {

        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                rootView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                sw_refresh.setRefreshing(true);
                query();
            }
        });

        sw_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                query();
            }
        });

        adapter.setOnRecyclerViewListener(new OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                if(position==0){
                    startActivity(NewFriendActivity.class,null);
                }else{
                    Friend friend = adapter.getItem(position);
                    User user = friend.getFriendUser();
                    BmobIMUserInfo info = new BmobIMUserInfo(user.getObjectId(), user.getUsername(), user.getAvatar());
                    BmobIMConversation conversationEntrance = BmobIM.getInstance().startPrivateConversation(info, null);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("c",conversationEntrance);
                    startActivity(ChatActivity.class,bundle);
                }
            }

            @Override
            public boolean onItemLongClick(int position) {

                if(position==0){
                    return true;
                }

                Friend friend = adapter.getItem(position);
                UserModel.getInstance().deleteFriend(friend, new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if(e==null){
                            toast("好友删除成功");
                            adapter.remove(position);
                        }else{
                            toast("好友删除失败："+e.getMessage());
                        }
                    }
                });

                return true;
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        query();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    @Subscribe
    public void onEventMainThread(RefreshEvent event){
        adapter.notifyDataSetChanged();
    }

    /**
     * 查询本地会话
     */
    private void query() {
        UserModel.getInstance().queryFriends(new FindListener<Friend>() {
            @Override
            public void done(List<Friend> list, BmobException e) {
                if(e==null){
                    List<Friend> friends=new ArrayList<>();
                    friends.clear();

                    for (int i=0;i<list.size();i++){
                        Friend friend = list.get(i);
                        String username = friend.getFriendUser().getUsername();
                        if(username!=null){
                            String pinyin = Pinyin.toPinyin(username.charAt(0));
                            friend.setPinyin(pinyin.substring(0,1).toUpperCase());
                            friends.add(friend);
                        }
                    }

                    adapter.bindDatas(friends);
                    adapter.notifyDataSetChanged();
                    sw_refresh.setRefreshing(false);

                }else{
                    adapter.bindDatas(null);
                    adapter.notifyDataSetChanged();
                    sw_refresh.setRefreshing(false);

                }
            }
        });
    }
}
